﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NamedPipeWrapper;
using CameraService;
using Com.Mc.Common.Cameras.Common;
using CommonProjects.FaceDetetive.EventArgs;
using CommonProjects.FaceFeatureContex;
using FaceCoreBase.Models;
using Common.Logging;
using PluginService.Common.Model;
using PluginService.Common;
using PluginService.Base;

namespace PluginService
{
    public class FaceDeteiveServiceNamedPipeHelper:FaceDeteiveServiceHelper
    {

        #region 变量

        
        protected Dictionary<string, NamedPipeClient<byte[]>> _connections = new Dictionary<string, NamedPipeClient<byte[]>>();

        protected NamedPipeClient<FaceCmpResultArgs> _pluginServicePipeClient;

        protected NamedPipeServer<PluginMessage<FaceFeatureItem>> _blankPipeServer;

        protected NamedPipeServer<PluginMessage<FaceDeteiveFeatureResult>> _faceDeteivePipeServer;
        

        #endregion

        #region 公共方法



        #endregion

        #region ovveride

        protected override void InitBlankData()
        {
            
        }

        protected override void HandStartCommand()
        {
            base.HandStartCommand();
            try
            {
                foreach(var p in _connections.Values)
                {
                    p.Start();
                }
                _blankPipeServer.Start();
                _faceDeteivePipeServer.Start();
                _pluginServicePipeClient.Start();
            }
            catch (Exception ex)
            {
                _log.Error(ex);
            }
        }


        protected override void InitConntection()
        {
            InitCameraConnection();
            _blankPipeServer = new NamedPipeWrapper.NamedPipeServer<PluginMessage<FaceFeatureItem>>(Consts.BLANK_PIPE_NAME);
            _blankPipeServer.ClientMessage += new ConnectionMessageEventHandler<PluginMessage<FaceFeatureItem>, PluginMessage<FaceFeatureItem>>(BlankPipe_ClientMessage);
            _blankPipeServer.ClientConnected += new ConnectionEventHandler<PluginMessage<FaceFeatureItem>, PluginMessage<FaceFeatureItem>>(BlankPipeServer_ClientConnected);
            _blankPipeServer.Error += new PipeExceptionEventHandler(Pipe_Error);

            _faceDeteivePipeServer = new NamedPipeServer<PluginMessage<FaceDeteiveFeatureResult>>(Consts.DETECTIVE_PIPE_NAME);
            _faceDeteivePipeServer.ClientConnected += new ConnectionEventHandler<PluginMessage<FaceDeteiveFeatureResult>, PluginMessage<FaceDeteiveFeatureResult>>(FaceDeteivePipeServer_ClientConnected);
            _faceDeteivePipeServer.ClientMessage += new ConnectionMessageEventHandler<PluginMessage<FaceDeteiveFeatureResult>, PluginMessage<FaceDeteiveFeatureResult>>(FaceDeteivePipe_ClientMessage);
            _faceDeteivePipeServer.Error += new PipeExceptionEventHandler(Pipe_Error);

            _pluginServicePipeClient = new NamedPipeClient<FaceCmpResultArgs>(Consts.COMPARE_SUCCESS_PIPE_NAME);
            _pluginServicePipeClient.ServerMessage += new ConnectionMessageEventHandler<FaceCmpResultArgs, FaceCmpResultArgs>(PluginServicePipeClient_ServerMessage);
            _pluginServicePipeClient.Error += new PipeExceptionEventHandler(Pipe_Error);
            _pluginServicePipeClient.AutoReconnect = true;

        }

        void BlankPipeServer_ClientConnected(NamedPipeConnection<PluginMessage<FaceFeatureItem>, PluginMessage<FaceFeatureItem>> connection)
        {
            _log.Info("黑名单添加客户端继");
        }



        void Pipe_Error(Exception exception)
        {
            _log.Error(exception);
        }

      

        void FaceDeteivePipeServer_ClientConnected(NamedPipeConnection<PluginMessage<FaceDeteiveFeatureResult>, PluginMessage<FaceDeteiveFeatureResult>> connection)
        {
            _log.Info("人脸检测有客户端接入");
        }

        protected virtual void PluginServicePipeClient_ServerMessage(NamedPipeConnection<FaceCmpResultArgs, FaceCmpResultArgs> connection, FaceCmpResultArgs message)
        {
            throw new NotImplementedException();
        }

        protected virtual void InitCameraConnection()
        {
            foreach (var cameraId in _cameraManager.CaptureIds)
            {
                //var displayInfo = _displayAndAlarmConfig.Where(a => a.CameraId == cameraId).FirstOrDefault();
                //if (displayInfo != null)
                //{
                    NamedPipeClient<byte[]> namedPipe = new NamedPipeClient<byte[]>(cameraId);
                    namedPipe.AutoReconnect = true;
                    namedPipe.Disconnected += new ConnectionEventHandler<byte[], byte[]>(namedPipe_Disconnected);
                    namedPipe.Error += new PipeExceptionEventHandler(Pipe_Error);
                    //namedPipe.Start();
                    _connections.Add(cameraId, namedPipe);
                //}
                //else
                //{
                //    throw new ArgumentException("配置文件错误Camera.json中的ID与DisplayAndAlarmConfig.json中的CameraID不一致，或无法找到");
                //}
            }
        }



        protected virtual void namedPipe_Disconnected(NamedPipeConnection<byte[], byte[]> connection)
        {
            
        }

        protected override void SendImageData(string id, byte[] data,CameraInfor info)
        {
            if (!string.IsNullOrEmpty(id))
            {
                if (_connections.ContainsKey(id))
                {
                    var connection = _connections[id];
                    connection.PushMessage(data);
                }
            }
        }

        protected override void SendCompareResult(CommonProjects.FaceDetetive.EventArgs.FaceCmpResultArgs args)
        {
            try
            {
                _pluginServicePipeClient.PushMessage(args);
            }
            catch (Exception ex)
            {
                _log.Error(ex);
            }
            
        }

        protected virtual void FaceDeteivePipe_ClientMessage(NamedPipeConnection<PluginMessage<FaceDeteiveFeatureResult>, PluginMessage<FaceDeteiveFeatureResult>> connection, PluginMessage<FaceDeteiveFeatureResult> message)
        {
            
            if (message != null && _faceDeteiveManager != null)
            {
                if (message.MessageBody != null)
                {
                    FaceDeteiveFeatureResult result = null;
                    if (message.MessageBody.ImageBytes != null)
                    {
                        result = _faceDeteiveManager.GetFaceFeature(message.MessageBody.ImageBytes);
                    }

                    if (result != null)
                    {
                        result.ImageBytes = message.MessageBody.ImageBytes;
                        result.Image = message.MessageBody.Image;
                    }
                    _faceDeteivePipeServer.PushMessage(new PluginMessage<FaceDeteiveFeatureResult>()
                    {
                        MessageBody = result
                    });
                }
            }
        }

        protected virtual void BlankPipe_ClientMessage(NamedPipeConnection<PluginMessage<FaceFeatureItem>, PluginMessage<FaceFeatureItem>> connection, PluginMessage<FaceFeatureItem> message)
        {
            //if (message != null && _faceDeteiveManager != null)
            //{
            //    _faceDeteiveManager.AddStorageCacheItem(message.MessageBody);
            //}
            AddBlankToFaceDeteiveManager(message.MessageBody);
        }

        protected virtual void AddBlankToFaceDeteiveManager(FaceFeatureItem faceFeatureItem)
        {
            if (_faceDeteiveManager != null && faceFeatureItem != null)
            {
                _faceDeteiveManager.AddStorageCacheItem(faceFeatureItem);
            }
        }

        #endregion

        #region IDispose

        public new void Dispose()
        {
            try
            {
                foreach (var pipe in _connections.Values)
                {
                    pipe.Stop();
                }
                _pluginServicePipeClient.Stop();
            }
            catch(Exception ex)
            {
                _log.Error(ex);
            }

            if (_pluginServicePipeClient != null)
            {
                _pluginServicePipeClient.Stop();
            }

            if (_blankPipeServer != null)
            {
                _blankPipeServer.Stop();
            }

            if (_faceDeteivePipeServer != null)
            {
                _faceDeteivePipeServer.Stop();
            }

            base.Dispose();
        }


        #endregion
    }
}
